package no.ntnu.item.ttm4115.termproject.gpsagent.data;

import java.io.*;
import java.util.*;
import javax.comm.*;

public class GpsReadNew extends Thread {
	static CommPortIdentifier portId;
	static Enumeration portList;
	
	static List dataList; 

	InputStream inputStream;
	SerialPort serialPort;

	
	public static void main(String[] args) {
		System.out.println("inne i main");
		GpsReadNew reader = new GpsReadNew();
	}


	public GpsReadNew(){
		try{
			System.setProperty("driver", "gnu.io.RXTXCommDriver");
			//System.setProperty("-Djava.library.path",".");
			// copy rxtxSerial.dll to the ..\jredirectory\bin
			System.loadLibrary("rxtxSerial");

		}
		catch(Exception e){
			System.err.println("Err: in loading properties");
		}
		
		portList = CommPortIdentifier.getPortIdentifiers();

		while (portList.hasMoreElements()) {
			System.out.println("er inne i while");
			portId = (CommPortIdentifier) portList.nextElement();
			if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
				if (portId.getName().equals("COM3")) {
					
					// start thread
					// open port
					try {
						System.out.println("opner port");
						serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
						
						try {
							serialPort.setSerialPortParams(38400,
									SerialPort.DATABITS_8,
									SerialPort.STOPBITS_1,
									SerialPort.PARITY_NONE);
						} catch (UnsupportedCommOperationException e) {System.out.println(e);}
					} catch (PortInUseException e) {
						serialPort.close();
						System.out.println("Port in use ..i will stop now...restart your application");
						System.out.println(e);
					}
					break;
				}
			}
		}
		
		System.out.println("thread starting...");
		this.start();
	}
	
	public void run() {
		
		//sleeping for the first time
		try {
			System.out.println("thread sleeping...initially");
			sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		

		
		while(true){
		try {
			inputStream = serialPort.getInputStream();
		} catch (IOException e) {System.out.println(e);}
/*		try {
			serialPort.addEventListener(this);
		} catch (TooManyListenersException e) {System.out.println(e);}*/
/*		serialPort.notifyOnDataAvailable(true);
		try {
			serialPort.setSerialPortParams(38400,
					SerialPort.DATABITS_8,
					SerialPort.STOPBITS_1,
					SerialPort.PARITY_NONE);
		} catch (UnsupportedCommOperationException e) {System.out.println(e);}*/
		//readThread = new Thread(this);
		//readThread.start();
		   dataList = new LinkedList();
			byte[] readBuffer = new byte[5000];
			int pos = 0;
			try {
				// reading the data available at the inputstream
				while (inputStream.available() > 0) {			
					byte[] srcBuffer = new byte[20];
					int numBytes = inputStream.read(srcBuffer);		
					
					if(numBytes>0){
						System.out.println("rb: "+ srcBuffer+" "+readBuffer+" "+ pos+" "+ numBytes);
						System.arraycopy(srcBuffer, 0, readBuffer, pos, numBytes);
					}
					
					pos = pos + numBytes;
				}
				// putting the data into the linked list
				dataList.add(new String(readBuffer,0,pos));
			} catch (Exception e) {e.printStackTrace();}
			
			// populating the data as string..retrieving from linked list
			String data="";
			Iterator i = dataList.iterator();
			while(i.hasNext()){
				data+=i.next();
			}
			
			// spliting the data into sentences (lines)
			String [] temp = data.split("\n");
			for(int j=0;j<temp.length;j++){
				String [] temprmc = temp[j].split(",");
				if(temp[j].contains("$GPRMC") && (temprmc.length>=7)) // to make sure that sufficient information is available
				{
					System.out.println("parsed: "+ parseGPRMC(temp[j]));
				}
			}
			
			// sleeping before to read new data
			try {
				System.out.println("thread sleeping....inbetween");
				sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	// method to parse GPRMC string
	/* $GPRMC,004007,V,3748.410,N,12226.632,W,000.0,360.0,130102,015.7,E*6F */
	/* $GPRMC,time,V or A,ddmm.mmm,N or S,dddmm.mmm,W or E,000.0,360.0,130102,015.7,E*6F */
	public String parseGPRMC(String data)
	{
		//System.out.println("GPRMC String: "+ data);
		String computed = "";
		String lat = "", latSgn = "", lon = "", lonSgn = "";
		String nmeaKey = "";
		try { nmeaKey = data.substring(3, 6) ;}
		catch (Exception e)
		{ return ""; }
		if (nmeaKey.equals("RMC"))
		{	//System.out.println("key: "+ nmeaKey);
			/* $GPRMC,004007,V,3748.410,N,12226.632,W,000.0,360.0,130102,015.7,E*6F */
			if (data.indexOf(",V,") > -1)
			{  // That's what we're interested in.
				// Example : [$GPRMC,004007,A,3748.410,N,12226.632,W,000.0,360.0,130102,015.7,E*6F]
				String tmp = data.substring(data.indexOf(",V,") + ",V,".length());  
				// tmp is now : [3748.410,N,12226.632,W,000.0,360.0,130102,015.7,E*6F]
				if (tmp.indexOf(",") > -1) // Latitude Value
				{
					lat = tmp.substring(0, tmp.indexOf(","));
					tmp = tmp.substring(tmp.indexOf(",") + ",".length());
					// tmp is now : [N,12226.632,W,000.0,360.0,130102,015.7,E*6F]
				}
				if (tmp.indexOf(",") > -1) // Latitude Sign
				{
					latSgn = tmp.substring(0, tmp.indexOf(","));
					tmp = tmp.substring(tmp.indexOf(",") + ",".length());
					// tmp is now : [12226.632,W,000.0,360.0,130102,015.7,E*6F]
				}
				if (tmp.indexOf(",") > -1) // Longitude Value
				{
					lon = tmp.substring(0, tmp.indexOf(","));
					tmp = tmp.substring(tmp.indexOf(",") + ",".length());
					// tmp is now : [W,000.0,360.0,130102,015.7,E*6F]
				}
				if (tmp.indexOf(",") > -1) // Longitude Sign
				{
					lonSgn = tmp.substring(0, tmp.indexOf(","));
					tmp = tmp.substring(tmp.indexOf(",") + ",".length());
					// tmp is now : [000.0,360.0,130102,015.7,E*6F]
				}
			}
		}
		if (lat.length() > 0)
		{
			if (lat.indexOf(".") > -1)
			{
				String s = lat.substring(0, lat.indexOf("."));
				s = s.substring(0, s.length() - 2) + "\272" + lat.substring(s.length() - 2);
				lat = s;
			}
		}
		else
			lat = "Not Set";
		if (lon.length() > 0)
		{
			if (lon.indexOf(".") > -1)
			{
				String s = lon.substring(0, lon.indexOf("."));
				s = s.substring(0, s.length() - 2) + "\272" + lon.substring(s.length() - 2);
				lon = s;
			}
		}
		else
			lon = "Not Set";

		computed = latSgn + " " + lat + "/" + lonSgn + " " + lon;
		return computed;
	}	
}